import React, { forwardRef, useState, useImperativeHandle, useRef, useEffect } from "react";
import { Modal, Space, Button, Icon, Popover, message,Table, Divider } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import CircularJSON from 'circular-json'
import { pritConfigItem } from './ltalpFunc'
import AddLtalpPritConfig from './addLtalpPritConfig'


function PrtConfigBuy(props, ref) {
    const [itSkuStatus, setEditSkuStatus] = useState({
        status: false,
        index: -1
    })
    const [addPritVstatus, setAddpritVstatus] = useState(false)
    interface ColumnPropsType {
        index: number;
        name: string;
    }
    const [configDataUse, setConfigDataUse] = useState<any>([])
    const [pritConfigList, setPritConfigList] = useState([pritConfigItem])
    const [hidenAll, setHidenAll] = useState(true)
    const [isAddConter, setIsAddConter] = useState(false)

    useImperativeHandle(ref, () => ({
        setAddpritVstatusAllconet:(k) => {
            setAddpritVstatus(k)
            setIsAddConter(true)
        }
    }));
    const addLtaLpPrittable: ColumnProps<ColumnPropsType>[] = [
        {
            title: '序号',
            key: '0',
            align: "center",
            width: 68,
            render: (text: any, record: any, index: number) => {
                return `配置 ${index + 1}`
            }
        }, {
            title: '类型',
            key: '1',
            align: "center",
            width: 150,
            dataIndex: 'typeName'
        }, {
            title: 'sku价格，库存限制购',
            key: '2',
            align: "left",
            width: 310,
            render: (text: any, record: any, index: number) => {
                const itlenKey = `type${record.pritType}AllConfig`

                return (<>
                    {record[itlenKey].map((item, index) => {
                        return (<div key={index}>
                            <Space direction="vertical">
                                <Space>
                                    <span>{item.skymin} 元</span>
                                    <span>&lt;=SKU价格&lt;</span>
                                    <span>{item.skymax} 元</span>
                                </Space>
                                <Space>
                                    <span>{record.typeName}:{item.prit}{(record.pritType === '0' || record.pritType === '1') ? '元' : '折'}</span>
                                    <span>限领{item.lin}个</span>
                                    <span>{item.kucuntype == "0" ? '不限制库存' : item.kucuntype == "1" ? `库存(全部)` : item.kucuntype == "2" ? `库存(${item.bai}%)` : `库存(${item.len}个)`}</span>
                                </Space>
                            </Space>
                            {(index !== record[itlenKey].length - 1) && <Divider style={{
                                margin: '5px 0'
                            }}></Divider>}

                        </div>)
                    })}
                </>)
            }
        },
        //  {
        //     title: '最低sku',
        //     key: '3',
        //     align: "left",
        //     width: 220,
        //     render: (text: any, record: any, index: number) => {
        //         const itlenMinConfKey = `type${record.pritType}MinConfigStatus`
        //         const itlenMinKey = `type${record.pritType}MinConfig`
        //         if (!record[itlenMinConfKey]) return '/'
        //         const item: any = record[itlenMinKey]
        //         return <Space direction="vertical">
        //             <Space>
        //                 <span>{record.typeName}:{item.prit}{(record.pritType === '0' || record.pritType === '1') ? '元' : '折'}</span>
        //                 <span>限领{item.lin}个</span>
        //                 <span>{item.kucuntype == "0" ? '不限制库存' : item.kucuntype == "1" ? `库存(全部)` : item.kucuntype == "2" ? `库存(${item.bai}%)` : `库存(${item.len}个)`}</span>
        //             </Space>
        //             <Space size={2}>
        //                 同低SKU:{minskySeletcoption.find((items) => {
        //                     return items.value === item.minskust
        //                 })?.label}
        //             </Space>
        //         </Space>
        //     }
        // }, 
        // {
        //     title: 'sku设置',
        //     key: '4',
        //     align: "center",
        //     width: 131,
        //     render: (text: any, record: any, index: number) => {
        //         const titlecontent = skuSetingoptions.find((item) => {
        //             return item.value === record.skuSeting

        //         })
        //         return titlecontent ? titlecontent.label : '/'
        //     }
        // }, 
        {
            title: '适配最低优惠',
            key: '4',
            align: "center",
            width: 131,
            render: (text: any, record: any, index: number) => {
                if (record.aotoPrtMin) return '自动'
                return '不适配'
            }
        },
        {
            title: '小数位数',
            key: '5',
            align: "center",
            render: (text: any, record: any, index: number) => {
                const getTer = record.pritFlot

                return getTer === '0' ? '保留两位小数' : getTer === '1' ? '保留一位小数' : getTer === '2' ? '保留整数' : `手动输入: ${record.flotNum}`
            }
        }, {
            title: '操作',
            key: '5',
            align: "center",
            render: (text: any, record: any, index: number) => {
                return (<Space>
                    <Space>
                        <Button type="link" icon={<Icon type='EditIcon'></Icon>} onClick={() => {
                            // let interdf = -1
                            // addAllConfigData.forEach((itut, inter) => {
                            //     if (itut.selectConfigIndex === index) {
                            //         interdf = inter
                            //     }
                            // })
                            // if (interdf !== -1) {
                            //     //  message.error(`该配置项已被活动${interdf + 1} 引用，不可删除`)
                            //     Modal.warning({
                            //         title: '提示',
                            //         content: `该配置项已被活动${interdf + 1} 引用, 编辑后讲以新的配置重新填写数据！！！`,
                            //         onOk: () => {
                            //             setEditSkuStatus({
                            //                 status: true,
                            //                 index
                            //             })
                            //             setAddpritVstatus(true)
                            //         }
                            //     })
                            //     return
                            // }
                            setEditSkuStatus({
                                status: true,
                                index
                            })
                            setAddpritVstatus(true)
                        }}>编辑</Button>
                    </Space>
                    <Space>
                        {/* <Button type="link" disabled={editLtalpStatus.status} style={{ color: '#F11717' }} icon={<Icon type="DeleteIcon"></Icon>} onClick={() => {
                        onDeleteImageItem && onDeleteImageItem()
                    }}>删除</Button> */}
                        <Button type="link" style={{ color: '#F11717' }} icon={<Icon type="DeleteIcon"></Icon>} onClick={() => {
                            // let interdf = -1
                            // addAllConfigData.forEach((itut, inter) => {
                            //     if (itut.selectConfigIndex === index) {
                            //         interdf = inter
                            //     }

                            // })
                            // if (interdf !== -1) {
                            //     message.error(`该配置项已被活动${interdf + 1} 引用，不可删除`)
                            //     return
                            // }
                            // // pritConfigList.splice(index, 1)
                            const copyDATA = CircularJSON.parse(CircularJSON.stringify(configDataUse))
                            copyDATA.splice(index, 1)
                            setConfigDataUse([...copyDATA])
                        }}>删除</Button>
                    </Space>
                </Space>)
            }
        }]
    return <Space direction="vertical">
        <Button type="primary" size="mini" icon={<Icon type="AddIcon" />} onClick={() => {
            setEditSkuStatus({
                status: false,
                index: -1
            })
            setAddpritVstatus(true)
        }}>添加(价格,库存,限购)配置</Button>
        <Table scroll={{ y: 420 }} columns={addLtaLpPrittable} dataSource={configDataUse} style={{ width: '100%', height: 470 }} pagination={false} rowKey="index"></Table>
        <Modal
            title={<>
                {itSkuStatus.status ? '编辑配置' :
                    <div className="showStaterTot">
                        添加(价格,库存,限购)配置 (已添加 {pritConfigList.length} 个配置)
                        <Button type="link" size="mini" icon={<Icon
                            type={hidenAll ? "DirectionUpIcon" : "DirectionDownIcon"}
                        ></Icon>} onClick={() => {
                            setHidenAll(!hidenAll)
                            pritConfigList.forEach(item => {
                                item.showAll = !hidenAll
                            })
                            setPritConfigList([...pritConfigList])

                        }}>{hidenAll ? '收起' : '展开'}全部</Button>
                    </div>}</>}
            // title="添加(价格,库存,限购)配置"
            visible={addPritVstatus}
            width={1050}
            bodyBottomMask
            wrapClassName={'add-content-modal'}
            onCancel={() => { setAddpritVstatus(false) }}
            footer={
                <div className="bote" style={{
                    display: 'flex',
                    justifyContent: 'space-between'
                }}>
                    <div className="leter">

                        {!itSkuStatus.status && <Popover
                            content={(
                                <Space direction="vertical" >
                                    <div>这里可以添加多个价格配置</div>
                                    <div className="moter" style={{
                                        width: '100%',
                                        display: 'flex',
                                        justifyContent: 'flex-end'
                                    }}>
                                        {/* <Button size="mini" type="primary" onClick={() => {
                                                setShowAddCouponStuats(false)
                                            }}>知道了</Button> */}
                                    </div>
                                </Space>
                            )}
                        // visible={showAddCouponStuats}
                        >

                            <Button size="mini" onClick={() => {
                                pritConfigList.push(pritConfigItem)
                                setPritConfigList([...pritConfigList])
                            }} icon={
                                <Icon type="AddIcon"></Icon>}>
                                新增配置
                            </Button>

                        </Popover>}

                    </div>
                    <div className="rngdtrr">
                        <Space>
                            <Button type="primary" size="mini" onClick={() => {
                                // 检查添加项
                                const adds = JSON.parse(JSON.stringify(pritConfigList)).map((item, index) => {
                                    item.index = index
                                    return item
                                })
                                if (itSkuStatus.status) {
                                    console.log('编辑 需要重新填写数据')
                                    // props.getPrdListSkus && props.getPrdListSkus()
                                }
                                setAddpritVstatus(false)

                                props.addConfigAllFun && props.addConfigAllFun(adds)
                                if(isAddConter) {
                                    props.setcurrentAddContar && props.setcurrentAddContar('addCoupon')
                                    setIsAddConter(false)
                                }
                                setConfigDataUse([...adds])
                            }}>{!itSkuStatus.status ? '添加' : '保存'}</Button>
                            <Button size="mini" onClick={() => {
                                setAddpritVstatus(false)
                            }}>取消</Button>
                        </Space>
                    </div>
                </div>
            }>
            <Space direction="vertical" size={16} style={{ width: '100%' }}>
                {pritConfigList.map((item, index) => {
                    if (itSkuStatus.status && itSkuStatus.index != index) {
                        return null
                    }
                    return <div key={index}>
                        <AddLtalpPritConfig
                            configData={item}
                            indexItem={index}
                            itSkuStatus={itSkuStatus}
                            onDeleteImageItem={() => {
                                if (pritConfigList.length <= 1) {
                                    message.error('至少保留一个活动')
                                    return
                                }
                                pritConfigList.splice(index, 1)

                                setPritConfigList([...pritConfigList])
                            }}
                            onChangeItem={(e) => {

                                pritConfigList[index] = e
                                setPritConfigList([...pritConfigList])
                            }}
                        // onChangeItemStatus = {(e) => {
                        //     pritConfigList[index].status = e
                        //     setPritConfigList([...pritConfigList])
                        // }}
                        ></AddLtalpPritConfig>
                        {index !== pritConfigList.length - 1 && <Divider style={{
                            margin: '10px 0'
                        }}></Divider>}
                    </div>
                })}
            </Space>
        </Modal>
    </Space>
}
export default forwardRef(PrtConfigBuy)